package com.heima.wemedia.gateway.filter;

import com.heima.wemedia.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-10 9:31
 */
//全局过滤器，对所有请求都会生效
@Component
//@Order(0)
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //1.判断接口是否需要校验 http://localhost:8080/test%201 URL编码  getPath还原出原始路径 test 1
        String path = request.getURI().getPath();
        if(path.contains("login/in")){
            //是登录请求，继续放行
            return chain.filter(exchange);
        }

        //2.获取请求头中的token
        List<String> list = request.getHeaders().get("token");

        if(CollectionUtils.isEmpty(list)){
            //校验身份失败 返回401编码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        String token = list.get(0);

        try{
            //3.校验token是否被篡改或者过期
            Claims claimsBody = AppJwtUtil.getClaimsBody(token); //获取载荷
            int status = AppJwtUtil.verifyToken(claimsBody);
            if(1 == status || 2 == status){
                //token过期或者别篡改了
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //必须制定类型
            Long id = claimsBody.get("id", Long.class);
            //添加请求头 userId
            ServerHttpRequest newRequest = request.mutate().header("userId", id.toString()).build();
            //让request生效
            exchange.mutate().request(newRequest);
        }
        catch (SignatureException e){
            e.printStackTrace();
            //对篡改签名特殊处理
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        catch (Exception e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4.执行业务代码
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
